//
//  SYS_MessageStoreAddressListVC.m
//  System_App
//
//  Created by 魏配军 on 2017/12/4.
//  Copyright © 2017年 czy001. All rights reserved.
//

#import "SYS_MessageStoreAddressListVC.h"
#import "SYS_StoreAddressListModel.h"
#import "SYS_StoreAddressCell.h"
#import "SYS_MessageMemberDetailVC.h"

@interface SYS_MessageStoreAddressListVC ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>

/*************搜索视图************/
@property (nonatomic, strong) SYS_SearchView *searchView;
@property (nonatomic, strong) DSNewTableView *mainTableView;
@property (nonatomic, strong) SYS_DisplayWithBlankView *alertView;

@property (nonatomic, strong) NSMutableArray *totalGroupArray;
@property (nonatomic, strong) NSMutableArray *searchPersonArray;
/*************是否正在搜索************/
@property (nonatomic,assign) BOOL isSearch;

@end

@implementation SYS_MessageStoreAddressListVC

-(UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setNavigationBar];
    [self initWithUI];
    
}

#pragma mark -- setter and getter
- (void)setNavigationBar{
    self.title = @"门店通讯录";
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImage:@"SYS_Public_back" highImage:nil title:nil target:self action:@selector(backToPrevious)];
    self.view.backgroundColor = DGHColor(242, 242, 242);
}

#pragma mark   -------  UI  ---------
-(void) initWithUI
{
//    _searchView = [[SYS_SearchView alloc] initWithFrame:CGRectMake(0, 10, SCREENWIDTH, 40)];
//    _searchView.placeholder=@"请输入您要查找的人";
//    _searchView.isClickChange=NO;
//    _searchView.inputTF.tag=99999;
//    _searchView.inputTF.delegate=self;
//    [self.view addSubview:_searchView];
    
    _mainTableView=[[DSNewTableView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT-NavBarHeight) style:UITableViewStylePlain];
    _mainTableView.delegate=self;
    _mainTableView.dataSource=self;
    _mainTableView.backgroundColor=DSCOLOR_WHITE;
    _mainTableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_mainTableView];
    
    _alertView=[[SYS_DisplayWithBlankView alloc] initWithFrame:CGRectMake(0, 0, 150, 150)];
    _alertView.photo.image=[UIImage imageNamed:@"message_lianxirenbucz"];
    _alertView.title.text=@"你查找的人不存在，请重新搜索~";
    _alertView.center=CGPointMake(_mainTableView.center.x, 140);
    _alertView.hidden=YES;
    [self.view addSubview:_alertView];
    
    //请求门店通讯录
    _totalGroupArray=[NSMutableArray array];
    _searchPersonArray=[NSMutableArray array];
    [self requestStoreAddressList];
    
    //添加文本框通知中心
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gosave:) name:UITextFieldTextDidChangeNotification object:nil];
}

// 检测textfiled值得变化
- (void)gosave:(NSNotification *) Notification{
    UITextField * textField = Notification.object;
    
    if (textField.tag == 99999) {
        //这个if判断是根据textField的tag来确定的，用来监控textField的值变化
        [_searchPersonArray removeAllObjects];
        for (int index=0; index<_totalGroupArray.count; index++) {
            SYS_StoreAddressListModel *model=_totalGroupArray[index];
            for (int i=0; i<model.employeeList.count; i++) {
                SYS_EmployeeList *employeeModel=model.employeeList[i];
                if ([employeeModel.employeesName containsString:textField.text]) {
                    [_searchPersonArray addObject:employeeModel];
                }
            }
        }
        
        if (textField.text.length>0) {
            _isSearch=YES;
        }else{
            _isSearch=NO;
        }
        NSLog(@"-----%@-----",textField.text);
        if (_isSearch) {
            _alertView.hidden=_searchPersonArray.count?YES:NO;
        }else{
            _alertView.hidden=YES;
        }
        [_mainTableView reloadData];
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.view endEditing:YES];
    if (textField.tag == 99999) {
        //这个if判断是根据textField的tag来确定的，用来监控textField的值变化
        [_searchPersonArray removeAllObjects];
        for (int index=0; index<_totalGroupArray.count; index++) {
            SYS_StoreAddressListModel *model=_totalGroupArray[index];
            for (int i=0; i<model.employeeList.count; i++) {
                SYS_EmployeeList *employeeModel=model.employeeList[i];
                if ([employeeModel.employeesName containsString:textField.text]) {
                    [_searchPersonArray addObject:employeeModel];
                }
            }
        }
        
        if (textField.text.length>0) {
            _isSearch=YES;
        }else{
            _isSearch=NO;
        }
        if (_isSearch) {
            _alertView.hidden=_searchPersonArray.count?YES:NO;
        }else{
            _alertView.hidden=YES;
        }
        NSLog(@"-----%@-----",textField.text);
        [_mainTableView reloadData];
    }
    return YES;
}

#pragma mark  ---------------请求门店通讯录-------------
-(void) requestStoreAddressList
{
    NSString *sessino=[SYS_LoginModel instance].sessionInfo.session;
    UICKeyChainStore *keychainStore = [UICKeyChainStore keyChainStore];
    NSString *pid = [keychainStore stringForKey:@"pid"];
    
    NSDictionary *parma=@{@"session":sessino,@"storeId":_storeId,@"pid":pid};
    [SYS_HttpUtility getStoreEmplyeesListRequest:parma success:^(id returnValue) {
        if ([returnValue[@"flag"] isEqualToString:@"true"]) {
            NSArray *dataArray=returnValue[@"data"];
            for (int index=0; index<dataArray.count; index++) {
                SYS_StoreAddressListModel *model=[SYS_StoreAddressListModel mj_objectWithKeyValues:dataArray[index]];
                /********************默认展开************************/
                model.isExpland=YES;
                
                NSMutableArray *empleeArray=[NSMutableArray array];
                /********************每组内的人员************************/
                for (int i=0; i<model.employeeList.count; i++) {
                    SYS_EmployeeList *empleeModel=[SYS_EmployeeList mj_objectWithKeyValues:model.employeeList[i]];
                    [empleeArray addObject:empleeModel];
                }
                model.employeeList=empleeArray;
                [_totalGroupArray addObject:model];
            }
            
            [_mainTableView reloadData];
        }else{
            [MBProgressHUD showSuccess:returnValue[@"exp"] toView:self.view];
        }
    } failure:^{
        RequestFailure;
        
    }];
}

#pragma mark   ----------------UITableViewDelegate,UITableViewDataSource---------
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (!_isSearch) {
        return _totalGroupArray.count;

    }
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (!_isSearch) {
        SYS_StoreAddressListModel *model=_totalGroupArray[section];
        if (model.isExpland) {
            return model.employeeList.count;
        }
        return 0;
    }else{
        return _searchPersonArray.count;
    }
    return 0;

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SYS_StoreAddressCell *cell = [[SYS_StoreAddressCell alloc]initWithTableView:tableView reuseId:@"SYS_StoreAddressCell"];
    if (!_isSearch) {
        SYS_StoreAddressListModel *model=_totalGroupArray[indexPath.section];
        SYS_EmployeeList *employeeModel=model.employeeList[indexPath.row];
        cell.employeeModel=employeeModel;
    }else{
        SYS_EmployeeList *employeeModel=_searchPersonArray[indexPath.row];
        cell.employeeModel=employeeModel;
    }

    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (!_isSearch) {
        return 40;
    }
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (!_isSearch) {
        UIView *bacview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 40)];
        bacview.backgroundColor = DGHColor(229, 247, 254);
        bacview.userInteractionEnabled=YES;
        UIView *lineView=[[UIView alloc]initWithFrame:CGRectMake(0, 39.5, SCREENWIDTH, 0.5)];
        lineView.backgroundColor=DGHColor(221, 221, 221);
        [bacview addSubview:lineView];
        SYS_StoreAddressListModel *model=_totalGroupArray[section];
        
        UIImageView *iconImageView=[[UIImageView alloc]initWithFrame:CGRectMake(10, 17, 8, 8)];
        if (model.isExpland) {
            iconImageView.image=[UIImage imageNamed:@"message_jiantoub"];
            
        }else{
            iconImageView.image=[UIImage imageNamed:@"message_jiantoua"];
            
        }
        [bacview addSubview:iconImageView];
        
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(iconImageView.frame)+10, 10, 150, 20)];
        titleLabel.text =model.groupName;
        titleLabel.textColor = DGHColorAlpha(20, 20, 20, 1);
        titleLabel.font = [UIFont systemFontOfSize:14];
        [bacview addSubview:titleLabel];
        
        UILabel *countLabel = [[UILabel alloc]initWithFrame:CGRectMake(SCREENWIDTH-100, 10, 90, 20)];
        countLabel.textAlignment=NSTextAlignmentRight;
        countLabel.text =FORMAT(@"%ld",model.employeeList.count);
        countLabel.textColor = DGHColorAlpha(168, 168, 168, 1);
        countLabel.font = [UIFont systemFontOfSize:12];
        [bacview addSubview:countLabel];
        
        bacview.tag=10000+section;
        UITapGestureRecognizer *ges=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(viewTapClick:)];
        [bacview addGestureRecognizer:ges];
        
        return bacview;
    }
    return nil;
}

-(void) viewTapClick:(UITapGestureRecognizer *) ges
{
    NSLog(@"%ld-",ges.view.tag);
    SYS_StoreAddressListModel *model=_totalGroupArray[ges.view.tag-10000];
    model.isExpland=!model.isExpland;
    [_mainTableView reloadData];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    SYS_MessageMemberDetailVC *vc=[SYS_MessageMemberDetailVC new];
    if (!_isSearch) {
        SYS_StoreAddressListModel *model=_totalGroupArray[indexPath.section];
        SYS_EmployeeList *employeeModel=model.employeeList[indexPath.row];
        vc.storeEmployeesId=employeeModel.storeEmployeesId;
    }else{
        SYS_EmployeeList *employeeModel=_searchPersonArray[indexPath.row];
        vc.storeEmployeesId=employeeModel.storeEmployeesId;

    }
    [self.navigationController pushViewController:vc animated:YES];
}


-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}


- (void)backToPrevious
{
    [self.navigationController popViewControllerAnimated:YES];
}

@end
